 //
//  MyProductsTool.m
//  GoBigMarket
//
//  Created by 王天义 on 16/9/9.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "MyProductsTool.h"
#import "MyProductModel.h"
#import "FMDB.h"

#define SQLITE_NAME @"product.sqlite"
#define DBPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:SQLITE_NAME]

@implementation MyProductsTool

#pragma mark --- 更新点击加减按钮后数据库商品信息数量
+ (void)ClickJiaJianProduct:(NSInteger)productId andCount:(NSInteger)count blockcompletion:(changeProduct)ChangProductblock{
    DLog(@"%@", DBPath);
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];

    //判断商品数量不能小于0
    if (count < 0) {
        return;
    }
    
    if (![database open]) {
        DLog(@"数据库打开失败");
        return;
    }else{
        
        if ([MyProductsTool queryByCondition:productId] == 0) {
            BOOL insert = [database executeUpdate:@"insert into myproduct values (?,?,?)",[NSNumber numberWithInteger:productId],[NSNumber numberWithInteger:count],GETPHONE];
            
            if (insert) {
                DLog(@"插入数据成功");
            }
        }
        
        
        BOOL update = [database executeUpdate:@"update myproduct set count = ? where productId = ? and phone = ? ",[NSNumber numberWithInteger:count],[NSNumber numberWithInteger:productId],GETPHONE];
        
        ChangProductblock(update);
    }

    [database close];
}

#pragma mark --- 删除数据库全部购物车商品信息
+ (void)deleteAllProductsFromSQL{
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    DLog(@"%@",DBPath);
    if (![database open]) {
        DLog(@"数据库打开失败");
        return;
    }
    
    BOOL delete = [database executeUpdate:@"delete from myproduct"];
    if (delete) {
        DLog(@"删除数据库表格成功");
    }
    
    [database close];
}

#pragma mark --- 删除数据库指定商品信息
+ (void)deleteOneProductsFromSQL:(NSInteger)productId{
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    if (![database open]) {
        DLog(@"数据库打开失败");
        return;
    }
    
    BOOL delete = [database executeUpdate:@"delete from myproduct where productId = ? and phone = ? ",[NSNumber numberWithInteger:productId],GETPHONE];
    if (delete) {
        DLog(@"删除数据成功");
    }
    
    [database close];
}

#pragma mark --- 从数据库查询全部购物车商品信息
+ (void)queryProductsFromSQLsuccess:(queryProductSuccess)querySuccesssblock failure:(queryProductFailure)queryFailureBlock{
    
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    
    
    if ([database open]) {
        FMResultSet *resultSet = [database executeQuery:@"select * from myproduct where phone = ?",GETPHONE];
        NSMutableArray *cartDatas = [[NSMutableArray alloc]init];

        while ([resultSet next]) {
            
            MyProductModel *model = [[MyProductModel alloc]init];
            model.productId = [resultSet intForColumn:@"productId"];
            model.count = [resultSet intForColumn:@"count"];

            [cartDatas addObject:model];
            
        }
        querySuccesssblock(cartDatas);

    }else{
        DLog(@"数据库打开失败");
//        NSError *error = [NSError setUserInfoValueProviderForDomain:@"打开数据库失败" provider:nil];
        queryFailureBlock(nil);
        DLog(@"Open database failed");
        return;
    }
    
    [database close];
    
}



#pragma mark --- 上传购物车数据
+ (void)getShopCartInfoRequest{
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if([isSignin_String isEqualToString:@"已登录"]){
        NSDictionary *par = @{@"ShouJiHao":GETPHONE,
                              @"Token":GETTOKEN,
                              @"Duuid":GETUUID,@"ShopId":GETShopId};
        
        [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:par success:^(id responseObject) {
            if ([[responseObject objectForKey:@"Err"] intValue] != 0) {
                DLog(@"%@",[responseObject objectForKey:@"ErrMsg"]);
            }else{
                
                NSArray *dataArr = [responseObject objectForKey:@"Products"];
                
                for (NSDictionary *dict in dataArr) {
                    MyProductModel *model = [[MyProductModel alloc]init];
                    model.productId = [[dict objectForKey:@"Id"]integerValue];
                    model.Count = [[dict objectForKey:@"Count"]integerValue];
                    
                    [self saveProductsInfo:model];
                }
                //创建一个消息对象
                NSNotification * noticelayoutRefresh = [NSNotification notificationWithName:@"layoutRefresh" object:nil userInfo:nil];
                //发送消息
                [[NSNotificationCenter defaultCenter]postNotification:noticelayoutRefresh];
            }
        } filed:^(NSError *error) {
            DLog(@"失败===%@", error);
            //[HUD error:@"请检查网络"];
        }];
    }
}

#pragma mark --- 单个执行条件查询操作
+ (int)queryByCondition:(NSInteger)productId {
    
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    if (![database open]) {
        DLog(@"数据库打开失败");
        return 0;
    }else{
        FMResultSet *resultSet = [database executeQuery:@"select * from myproduct where productId = ? ",[NSNumber numberWithInteger:productId]];
        int count = 0;
        while ([resultSet next]) {
            count = [resultSet intForColumn:@"count"];
        }
        return count;
    }
}

#pragma mark --- 批量执行条件查询操作
+ (void)queryByCondition:(NSMutableArray *)productIdArr success:(queryProductSuccess)querySuccesssblock failure:(queryProductFailure)queryFailureBlock{
    
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    if (![database open]) {
        DLog(@"数据库打开失败");
        queryFailureBlock(nil);
    }else{
        NSMutableArray *productArr = [NSMutableArray array];
        
        for (NSNumber *productId in productIdArr) {
            FMResultSet *resultSet = [database executeQuery:@"select * from myproduct where productId = ? ",productId];
            MyProductModel *model = [[MyProductModel alloc]init];
            while ([resultSet next]) {
                model.Count = [resultSet intForColumn:@"count"];
                model.productId = [resultSet intForColumn:@"productId"];

                [productArr addObject:model];
            }
           
        }
        querySuccesssblock(productArr);
        
    }
}

+ (void)saveProductsInfo:(MyProductModel *)model{
    FMDatabase *database = [FMDatabase databaseWithPath:DBPath];
    if (![database open]) {
        DLog(@"数据库打开失败");
        DLog(@"Open database failed");
        return;
    }
    
    
    
    BOOL insert = [database executeUpdate:@"insert into myproduct values (?,?,?)",[NSNumber numberWithInteger:model.productId],[NSNumber numberWithInteger:model.Count],GETPHONE];
    
    if (insert) {
        
        DLog(@"插入数据成功");
    }else{
        
    [database executeUpdate:@"create table myproduct (productId integer,count integer,phone integer)"];
        
    }
    
    [database close];
}

@end
